﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Hammock.Authentication.OAuth;
using Hammock;
using Hammock.Silverlight.Compat;
using System.IO.IsolatedStorage;
using System.ComponentModel;

namespace Tsina
{
    public partial class Authentication : PhoneApplicationPage
    {
        private string requestToken;
        private string requestTokenSecret;

        public Authentication()
        {
            InitializeComponent();

            GetRequestToken();
        }

        private void GetRequestToken()
        {
            var credentials = new OAuthCredentials()
            {
                Type = OAuthType.RequestToken,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                ConsumerKey = ConfigHelper.AppKey,
                ConsumerSecret = ConfigHelper.AppSecret
            };

            var client = new RestClient();

            var request = new RestRequest()
            {
                Path = ConfigHelper.RequestTokenUrl,
                Credentials = credentials
            };

            client.BeginRequest(request, CompleteGetRequestToken);
        }

        private void CompleteGetRequestToken(RestRequest request, RestResponse response, object userState)
        {
            NameValueCollection values = System.Web.HttpUtility.ParseQueryString(response.Content);

            requestToken = values["oauth_token"];
            requestTokenSecret = values["oauth_token_secret"];

            string authorizeUrlWithParameters = ConfigHelper.AuthorizeUrl + "?oauth_token=" + requestToken + "&oauth_callback=" + HttpUtility.UrlEncode("http://localhost/fake.aspx");

            this.Dispatcher.BeginInvoke(() => this.webBrowser1.Navigate(new Uri(authorizeUrlWithParameters)));
        }

        private void webBrowser1_Navigating(object sender, NavigatingEventArgs e)
        {
            if (e.Uri.AbsoluteUri.StartsWith("http://localhost/fake.aspx") == true)
            {
                e.Cancel = true;
                this.webBrowser1.Navigating -= webBrowser1_Navigating;
                this.webBrowser1.Visibility = Visibility.Collapsed;
                NameValueCollection queryStrings = System.Web.HttpUtility.ParseQueryString(e.Uri.AbsoluteUri.Split('?')[1]);
                string verifier = queryStrings["oauth_verifier"];
                GetAccessToken(verifier);
            }
        }

        private void GetAccessToken(string verifier)
        {
            var credentials = new OAuthCredentials()
            {
                Type = OAuthType.AccessToken,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                ConsumerKey = ConfigHelper.AppKey,
                ConsumerSecret = ConfigHelper.AppSecret,
                Token = requestToken,
                TokenSecret = requestTokenSecret,
                Verifier = verifier
            };

            var client = new RestClient();

            var request = new RestRequest()
            {
                Path = ConfigHelper.AccessTokenUrl,
                Credentials = credentials
            };

            client.BeginRequest(request, CompleteGetAccessToken);
        }

        private void CompleteGetAccessToken(RestRequest request, RestResponse response, object userState)
        {
            NameValueCollection values = System.Web.HttpUtility.ParseQueryString(response.Content);

            ConfigHelper.AccessToken = values["oauth_token"];
            ConfigHelper.AccessTokenSecret = values["oauth_token_secret"];
            ConfigHelper.UserId = values["user_id"];

            IsolatedStorageSettings.ApplicationSettings[ConfigHelper.AccessTokenString] = ConfigHelper.AccessToken;
            IsolatedStorageSettings.ApplicationSettings[ConfigHelper.AccessTokenSecretString] = ConfigHelper.AccessTokenSecret;
            IsolatedStorageSettings.ApplicationSettings[ConfigHelper.UserIdString] = ConfigHelper.UserId;

            this.Dispatcher.BeginInvoke(() => this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative)));
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }
    }
}